package hello;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

import persistence.HibernateUtil;
import auction.model.Category2OneToManyEntity;
import auction.model.CategoryItem2OneToManyEntity;
import auction.model.Item2OneToManyEntity;
import auction.model.CategoryItem2OneToManyEntity.Id;

public class HelloWorld2OneToManyEntity
{
	
	
	public static void main(String[] args)throws Exception
	{

		
		Session s=HibernateUtil.getSessionFactory().openSession();
		Transaction tx=s.beginTransaction();

		
		Category2OneToManyEntity catA =new Category2OneToManyEntity("cat a "+new Date());
		Item2OneToManyEntity iA=new Item2OneToManyEntity("item a "+new Date());
		/*
		s.save(catA);
		s.save(iA);
		
		CategoryItem2OneToManyEntity link =new CategoryItem2OneToManyEntity("www",catA,iA);
		s.save(link);
		*/
		
		tx.commit();
		s.close();
		
		
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		
		Category2OneToManyEntity catout=(Category2OneToManyEntity)s1.load(Category2OneToManyEntity.class,3L);
		Item2OneToManyEntity iout=(Item2OneToManyEntity)s1.load(Item2OneToManyEntity.class,3L);
		Item2OneToManyEntity i2add=(Item2OneToManyEntity)s1.load(Item2OneToManyEntity.class,2L);
		
		Id delId=new Id(catout.getId(),iout.getId());
		
		CategoryItem2OneToManyEntity delLink=null;
		for(CategoryItem2OneToManyEntity linktmp : catout.getCategorizedItems()){
			if(linktmp.getId().equals(delId)){
				delLink=linktmp;
			}
		}
		//remove item3 from cat3
		s1.delete(delLink);
		
		//add item2 to cat3
		CategoryItem2OneToManyEntity newlink =new CategoryItem2OneToManyEntity("www",catout,i2add);
		s1.save(newlink);
		
		//catout.getCategorizedItems().remove(delLink);
		//out("#### "+catout.getCategorizedItems().size());
		
		tx1.commit();
		s1.close();
		
		
		
		//HibernateUtil.stat();
		HibernateUtil.shutdown();
	
	}
	
	public static void getParent(Class clazz)
	{
		Class parent=clazz.getSuperclass();
	  if(parent !=null)
	  {
			System.out.println("###"+parent.getName());
			getParent(parent);
		}
	}
	
	static void out(Object obj)
	{
		System.out.println(obj);
	}
}
